package tt.dz.egobus.servicemanager.core.config;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

import static tt.dz.egobus.servicemanager.core.config.RuntimeConfigKeyEnum.BUSINESS_GRAB_BUS_DISTRIBUTE_MAX_SEARCH_LIMIT;
import static tt.dz.egobus.servicemanager.core.config.RuntimeConfigKeyEnum.DRIVER_BUSINESS_GRAB_TIMEOUT;
import static tt.dz.egobus.servicemanager.core.config.RuntimeConfigKeyEnum.USER_BUSINESS_BUS_REQUEST_TIMEOUT;

/**
 * @author Anson
 * @date 17-8-8
 * @name 默认配置获取器
 * @since 1.0.6
 */
public class DefaultValueConfigAccess extends AbstractConfigAccess {

    private final Map<String, RuntimeConfigKeyEnum> defaultConfigAccess = new HashMap<String, RuntimeConfigKeyEnum>();

    public DefaultValueConfigAccess() {
        this.putDefaultValueToMap(BUSINESS_GRAB_BUS_DISTRIBUTE_MAX_SEARCH_LIMIT);
        this.putDefaultValueToMap(DRIVER_BUSINESS_GRAB_TIMEOUT);
        this.putDefaultValueToMap(USER_BUSINESS_BUS_REQUEST_TIMEOUT);
    }

    @Override
    public <T> T value(String key, Class<T> clazz) {
        return this.value(key, (T) null);
    }

    @Override
    public <T> T value(String key, T defaultValue) {
        RuntimeConfigKeyEnum configKeyEnum = RuntimeConfigKeyEnum.indexOf(key);
        if (configKeyEnum == null) {
            return defaultValue;
        }
        String fullKey = this.keyRuntimeConfigKeyEmunConvert(configKeyEnum);
        if (StringUtils.isBlank(fullKey)) {
            return defaultValue;
        }
        RuntimeConfigKeyEnum runtimeConfigKeyEnum = this.defaultConfigAccess.get(fullKey);
        Object enumDefaultValue = runtimeConfigKeyEnum.getDefaultValue();
        if (enumDefaultValue == null ||
                defaultValue != null && !defaultValue.getClass().isAssignableFrom(enumDefaultValue.getClass())) {
            return defaultValue;
        }
        return (T) enumDefaultValue;
    }

    /**
     * 将枚举类转换一个map配置
     *
     * @param e
     */
    protected void putDefaultValueToMap(RuntimeConfigKeyEnum e) {
        defaultConfigAccess.putIfAbsent(this.keyRuntimeConfigKeyEmunConvert(e), e);
    }

}
